use std::fs::File;

fn main() {
  println!("~~~~");

  /** rust语言将错误分为两个类别: 可恢复错误 和 不可恢复错误*/
  // Recoverable Errors with Result
  // Unrecoverable Errors with panic!

  /** 1. Result<T,E>*/
  //+ (1) 可恢复错误通常代表向用户报告错误 和 重试操作是合理的情况, 例如未找到文件。 rust中使用 Result<T,E>来实现。
  /*enum Result<T,E> {
    Ok(T),
    Err(E)
  }  */
  /** 1.1*/
  /*let f = File::open("hello.txt");
  let r = match f {
    Ok(file) => file,
    Err(error) => panic!("error: {:?}", error) //'error: Os { code: 2, kind: NotFound, message: "系统找不到指定的文件。" }'
    /*
thread 'main' panicked at 'error: Os { code: 2, kind: NotFound, message: "系统找不到指定的文件。" }', 09.error-handling\src\main.rs:16:19
stack backtrace:
  ...
    */
  };
  println!("{:?}", r);*/
  //↑ 有点麻烦
  //↓ 可以这么简写
  /** 1.2 错误时会阻止程序向下运行(因为就是panic的语法糖)*/
  //let f = File::open("hello.txt").unwrap(); //thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "系统找不到指定的文件。" }', 09.error-handling\src\main.rs:26:35
  /** 1.3 相较上面的简写方式能自定义错误信息前缀
          上面的简写信息总是为 Err` value:*/
  /*let f = File::open("hello.txt")
    //Panics if the value is an Err, with a panic message including the passed message, and the content of the Err
    .expect("Failed to open hello.txt"); //thread 'main' panicked at 'Failed to open hello.txt: Os { code: 2, kind: NotFound, message: "系统找不到指定的文件。" }', 09.error-handling\src\main.rs:32:6*/

  /** 2. panic!() */
  //+ (2) 不可恢复错误是bug的同义词, 如尝试访问超过数组结尾的位置。 rust中通过 panic! 来实现

  // panic!("crash here !");
/*
thread 'main' panicked at 'crash here !', 09.error-handling\src\main.rs:15:3
stack backtrace:
   0: std::panicking::begin_panic<str>
             at /rustc/c8dfcfe046a7680554bf4eb612bad840e7631c4b\library\std\src\panicking.rs:541
   1: error_handling::main
             at .\09.error-handling\src\main.rs:15
   2: core::ops::function::FnOnce::call_once<void (*)(),tuple$<> >
             at /rustc/c8dfcfe046a7680554bf4eb612bad840e7631c4b\library\core\src\ops\function.rs:227
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
error: process didn't exit successfully: `target\debug\error-handling.exe` (exit code: 101)
*/

  /** 3. RUST_BACKTRACE=1 cargo run ---> 在 cargo run 之前, 将RUST_BACKTRACE=1, 能打印完整调用栈, 默认为0*/
  println!("~~~~");

}
